import {applySnapshot, getSnapshot, types} from 'mobx-state-tree';

// @ts-ignore
export const Menu = types
    .model("Menu", {
        id: types.identifier,
        label: types.string,
        path: types.string,
        icon: '',
        schema: types.frozen({}),
        children: types.array(types.late(() => Menu)),
    })
    .actions(self => {
        function addSubMenu(menu: IMenu) {
            self.children.push(menu);
        }

        return {
            addSubMenu
        };
    });

export type IMenu = typeof Menu.Type;

export const MenuStore = types
    .model('MenuStore', {
        menus: types.array(types.late(() => Menu)),
    })
    .views(self => ({}))
    .actions(self => {
        function load(): void {
            if (typeof window !== 'undefined' && window.localStorage) {
                const menusData = window.localStorage.getItem('menus');
                if (menusData) {
                    applySnapshot(self.menus, JSON.parse(menusData));
                } else {
                    let menu = Menu.create({
                        id: 'root',
                        label: 'root',
                        path: '/pageManage/root/',
                        schema: {
                            type: 'page',
                            title: '默认页面',
                            body: '默认页面'
                        }
                    });
                    self.menus.push(menu);
                }
            }
        }

        const clearMenuActive = (): void => {
            let clearActive = (menuArr: IMenu[]) => {
                menuArr.forEach((item: IMenu) => {
                    if (item.children && item.children.length > 0) {
                        clearActive(item.children)
                    }
                })
            }
            clearActive(self.menus)
        }

        const getMenuById = (menuId: string): IMenu => {

            let findActive = (menuArr: IMenu[], id: string): IMenu => {
                let result = undefined;
                menuArr.find((item: IMenu) => {
                    if (item.id == id) {
                        result = item
                        return true;
                    } else if (item.children && item.children.length > 0) {
                        result = findActive(item.children, id)
                        return result != undefined
                    } else {
                        return false;
                    }
                })
                return result;
            }
            return findActive(self.menus, menuId);
        }

        const saveMenus = (): void => {
            let data = getSnapshot(self)
            window.localStorage.setItem('menus', JSON.stringify(data.menus));
        }

        return {
            load,
            getMenuById,
            clearMenuActive,
            saveMenus
        };
    });

export type IMenuStore = typeof MenuStore.Type;
